<script setup lang="ts">
// ----------------------- 导入相关依赖 -----------------------
// Vue 核心功能
import {nextTick, onMounted, reactive, ref} from "vue";
// Element Plus 组件和类型
import {ElMessage, FormInstance} from "element-plus";
// 自定义组件和hooks
import SysDialog from "@/components/dialog/SysDialog.vue";
import useDialog from "@/hooks/useDialog";
import useInstance from "@/hooks/useInstance";
// API相关
import {MaterialCategory, MaterialCategoryListParam} from "@/api/materialCategory/type";
import {addApi, deleteApi, editApi, getListApi, getSimpleListApi} from "@/api/materialCategory/index.ts";
// 树形选择组件
import TreeSelect from "@/components/TreeSelect/index.vue";
// 图标组件
import {Search, Refresh, Plus, Edit, Delete} from '@element-plus/icons-vue'

// ----------------------- 组件状态定义 -----------------------
// 获取全局实例和弹框方法
const {dialog, onShow, onClose} = useDialog()
const {global} = useInstance()

// 当前选中的分类ID，用于树形筛选
const currentCategoryId = ref<number>()

// 查询表单数据，包含分页信息
const searchForm = reactive<MaterialCategoryListParam>({
  categoryCode: undefined,
  categoryName: undefined,
  parentId: undefined,
  page: 1,
  limit: 15
})


// 表格数据和总条数和加载效果
const tableData = ref([])
const total = ref(0)
const loading = ref(false)

// 表单ref，用于表单验证
const addFormRef = ref<FormInstance>()

// 初始化表单数据
const initForm = () => {
  return {
  id: undefined,
  categoryCode: undefined,
  categoryName: undefined,
  description: undefined,
  parentId: undefined,
  areaJudgment: undefined,
  weightJudgment: undefined,
  weightTotalJudgment: undefined,
  areaTotalJudgment: undefined
  }
}

// 新增/编辑表单数据
const addForm = reactive<MaterialCategory>(initForm())

// ----------------------- 表单验证规则 -----------------------
const rules = {
  categoryName: [{required: true, message: '请输入分类名称', trigger: 'blur'}],
  parentId: [{required: true, message: '请选择上级分类', trigger: 'change'}]
}

// ----------------------- 树形数据处理 -----------------------
// 上级分类选择器的数据
const parentOptions = ref<any[]>([])

/**
 * 获取上级分类列表数据
 * 用于新增/编辑表单中的上级分类选择
 */
const getParentCategories = async () => {
  try {
    const res = await getSimpleListApi()
    if (res?.data) {
      const treeData = handleParentTree(res.data)
      // 添加顶级节点
      parentOptions.value = [{
        id: '0',
        value: '0',
        label: '顶级分类',
        children: treeData
      }]
    }
  } catch (error) {
    console.error('获取上级分类列表失败:', error)
    ElMessage.error('获取上级分类列表失败')
  }
}

/**
 * 处理上级分类树形数据
 * @param data 原始数据
 * @returns 处理后的树形数据
 */
const handleParentTree = (data: any[]) => {
  const map = new Map()
  const result: any[] = []

  // 初始化映射表
  data.forEach(item => {
    map.set(item.id, {
      id: item.id,
      value: item.id,
      label: item.categoryName,
      children: []
    })
  })

  // 构建树形结构
  data.forEach(item => {
    const node = map.get(item.id)
    if (item.parentId === "0") {
      result.push(node)
    } else {
      const parent = map.get(item.parentId)
      if (parent) {
        parent.children.push(node)
      }
    }
  })
  return result
}

// ----------------------- 左侧筛选树形数据处理 -----------------------
// 定义树节点类型
interface TreeNode {
  id: string;
  categoryName: string;
  parentId: string;
  children: TreeNode[];
}

// 左侧筛选树形数据
const treeData = ref<TreeNode[]>([])

/**
 * 获取左侧筛选树形数据
 */
const getTreeData = async () => {
  try {
    const res = await getSimpleListApi()
    if (res?.data) {
      treeData.value = handleTree(res.data)
    }
  } catch (error) {
    console.error('获取树形数据失败:', error)
    ElMessage.error('获取分类数据失败')
  }
}

/**
 * 处理左侧筛选树形结构
 * @param data 原始数据
 * @returns 处理后的树形数据，包含虚拟顶级节点
 */
const handleTree = (data: TreeNode[]): TreeNode[] => {
  const map = new Map<string, TreeNode>();
  const result: TreeNode[] = [];

  // 创建虚拟的顶级节点
  const rootNode: TreeNode = {
    id: '-1',
    categoryName: '全部分类',
    parentId: '',
    children: [],
  };

  // 初始化映射表
  data.forEach((item) => {
    map.set(item.id, {...item, children: []});
  });

  // 构建树形结构
  data.forEach((item) => {
    const node = map.get(item.id)!;
    if (item.parentId === "0") {
      rootNode.children.push(node);
    } else {
      const parent = map.get(item.parentId);
      if (parent) {
        parent.children.push(node);
      }
    }
  });

  result.push(rootNode);
  return result;
};

// ----------------------- CRUD 操作方法 -----------------------
/**
 * 获取分类列表数据
 */
const getList = async () => {
  loading.value = true
  try {
    const res = await getListApi(searchForm)
    if (res?.data) {
      tableData.value = res.data.list
      total.value = res.data.total
    }
  } catch (error) {
    console.error('获取列表数据失败:', error)
    ElMessage.error('获取列表数据失败')
  }finally {
    loading.value = false
  }
}

/**
 * 重置查询表单
 */
const resetForm = () => {
  searchForm.categoryCode = undefined
  searchForm.categoryName = undefined
  searchForm.parentId = currentCategoryId.value || undefined
  searchForm.page = 1
  getList()
}

/**
 * 显示新增弹框
 */
const show = () => {
  dialog.title = '新增物料分类'
  dialog.width = 600
  dialog.height = 400
  // 确保表单数据完全重置
  Object.assign(addForm, initForm())
  onShow()
}

/**
 * 显示编辑弹框
 */
const edit = (row: MaterialCategory) => {
  dialog.title = '编辑物料分类'
  dialog.width = 600
  dialog.height = 400
  
  // 先重置表单，再填充数据
  Object.assign(addForm, initForm())
  
  nextTick(() => {
    // 清除表单验证状态
    addFormRef.value?.clearValidate()
    // 填充编辑数据
    Object.assign(addForm, row)
  })
  onShow()
}

/**
 * 删除分类
 */
const del = async (id: number) => {
  const confirm = await global.$myConfirm('您确定删除该数据吗？')
  if (confirm) {
    try {
      const res = await deleteApi(id)
      if (res && res.code === 200) {
        ElMessage.success('删除成功')
        getList()
        getTreeData() // 刷新树形数据
      }
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

/**
 * 保存分类（新增/编辑）
 */
const save = async () => {
  if (!addFormRef.value) return
  await addFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        let res
        if (addForm.id) {
          // 编辑时提交所有数据
          res = await editApi(addForm)
        } else {
          // 新增时不发送分类编码，让后端自动生成
          const submitData = { ...addForm }
          delete submitData.categoryCode
          res = await addApi(submitData)
        }
        if (res && res.code === 200) {
          ElMessage.success(addForm.id ? '修改成功' : '新增成功')
          // 重置表单
          addFormRef.value?.resetFields()
          addFormRef.value?.clearValidate()
          Object.assign(addForm, initForm())
          onClose()
          getList()
          getTreeData() // 刷新树形数据
        }
      } catch (error) {
        console.error('保存失败:', error)
        ElMessage.error('保存失败')
      }
    }
  })
}

// ----------------------- 分页相关方法 -----------------------
/**
 * 页码改变处理
 */
const handleCurrentChange = (val: number) => {
  searchForm.page = val
  getList()
}

/**
 * 每页条数改变处理
 */
const handleSizeChange = (val: number) => {
  searchForm.limit = val
  getList()
}

// ----------------------- 其他方法 -----------------------
/**
 * 关闭弹框
 */
const closeDialog = () => {
  // 延迟执行重置，确保弹窗完全关闭
  nextTick(() => {
    // 重置表单字段和验证状态
  addFormRef.value?.resetFields()
    addFormRef.value?.clearValidate()
    
    // 完全重置表单数据
    Object.assign(addForm, initForm())
  })
  onClose()
}

/**
 * 树节点点击事件处理
 */
const handleTreeNodeClick = async (data: any) => {
  // 处理虚拟顶级节点点击
  if (data.id === '-1') {
    currentCategoryId.value = undefined;
    searchForm.parentId = undefined;
  } else {
    currentCategoryId.value = data.id;
    searchForm.parentId = data.id;
  }

  // 重置分页和搜索条件
  searchForm.page = 1;
  searchForm.limit = 10;
  searchForm.categoryCode = undefined;
  searchForm.categoryName = undefined;

  await getList();
}

// 表格高度自适应
const tableHeight = ref(0)

// ----------------------- 生命周期钩子 -----------------------
onMounted(() => {
  // 设置表格高度
  nextTick(() => {
    tableHeight.value = window.innerHeight - 260
  })
  // 初始化数据
  getTreeData()
  getList()
  getParentCategories()
})
</script>

<template>
  <el-main class="material-category-main">
    <div class="main-container">
      <el-row :gutter="20">
        <!-- 左侧树形菜单 -->
        <el-col :span="6">
          <el-card class="tree-card" shadow="hover">
            <div class="tree-header">
              <i class="el-icon-menu"></i>
              <span>物料分类</span>
            </div>
            <TreeSelect
              :data="treeData"
              :props="{
                children: 'children',
                label: 'categoryName'
              }"
              placeholder="请输入分类名称"
              @node-click="handleTreeNodeClick"
              class="category-tree"
            />
          </el-card>
        </el-col>

        <!-- 右侧内容区 -->
        <el-col :span="18">
          <!-- 查询表单区域 -->
          <el-card class="search-card" shadow="hover">
            <el-form :inline="true" :model="searchForm" class="search-form">
              <el-form-item label="分类编码">
                <el-input 
                  v-model="searchForm.categoryCode" 
                  placeholder="请输入分类编码"
                  prefix-icon="Search"
                  clearable
                />
              </el-form-item>
              <el-form-item label="分类名称">
                <el-input 
                  v-model="searchForm.categoryName" 
                  placeholder="请输入分类名称"
                  prefix-icon="Search"
                  clearable
                />
              </el-form-item>
              <el-form-item class="search-buttons">
                <el-button type="primary" :icon="Search" @click="getList" class="search-btn">
                  查询
                </el-button>
                <el-button :icon="Refresh" @click="resetForm" class="reset-btn">
                  重置
                </el-button>
                <el-button type="success" :icon="Plus" @click="show" class="add-btn">
                  新增
                </el-button>
              </el-form-item>
            </el-form>
          </el-card>

          <!-- 表格区域 -->
          <el-card class="table-card" shadow="hover">
            <el-table
              v-loading="loading"
              :data="tableData"
              border
              :height="tableHeight"
              class="data-table"
            >
              <el-table-column type="index" label="序号" width="70" align="center"/>
              <el-table-column prop="categoryCode" label="分类编码" min-width="120" align="center"/>
              <el-table-column prop="categoryName" label="分类名称" min-width="120" align="center"/>
              <el-table-column prop="description" label="描述" min-width="180" align="center" show-overflow-tooltip/>
              <el-table-column prop="createTime" label="创建时间" min-width="170" align="center"/>
              <el-table-column prop="updateTime" label="更新时间" min-width="170" align="center"/>
              <el-table-column label="操作" width="160" fixed="right" align="center">
                <template #default="scope">
                  <div class="action-buttons">
                    <el-button type="primary" size="small" :icon="Edit" @click="edit(scope.row)" class="edit-btn">
                      编辑
                    </el-button>
                    <el-button type="danger" size="small" :icon="Delete" @click="del(scope.row.id)" class="delete-btn">
                      删除
                    </el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>

            <!-- 分页 -->
            <el-pagination
              v-model:current-page="searchForm.page"
              v-model:page-size="searchForm.limit"
              :page-sizes="[10, 20, 30, 40, 50]"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              layout="total, sizes, prev, pager, next, jumper"
              class="pagination"
            />
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 新增/编辑弹框 -->
    <sys-dialog
      :title="dialog.title"
      :width="dialog.width"
      :visible="dialog.visible"
      @onClose="closeDialog"
      @onConfirm="save"
      destroy-on-close
    >
      <template #content>
        <div class="dialog-content">
          <el-form
            ref="addFormRef"
            :model="addForm"
            :rules="rules"
            label-width="100px"
            class="add-form"
          >
            <el-card class="form-card" shadow="never">
              <template #header>
                <div class="form-header">
                  <span>基本信息</span>
                </div>
              </template>
              <el-form-item label="分类编码" prop="categoryCode">
                <el-input 
                  v-model="addForm.categoryCode" 
                  :placeholder="addForm.id ? '已生成编码' : '保存后自动生成'" 
                  readonly 
                  disabled
                  style="background-color: #f5f7fa;"
                />
                <div class="code-tip" v-if="!addForm.id">
                  保存后系统将自动生成：年月日+流水号
                </div>
                <div class="code-tip" v-else>
                  分类编码创建后不可修改
                </div>
              </el-form-item>
              <el-form-item label="分类名称" prop="categoryName">
                <el-input v-model="addForm.categoryName" placeholder="请输入分类名称" />
              </el-form-item>
              <el-form-item label="上级分类" prop="parentId">
                <el-tree-select
                  v-model="addForm.parentId"
                  :data="parentOptions"
                  :render-after-expand="false"
                  show-checkbox
                  check-strictly
                  class="full-width"
                />
              </el-form-item>
            </el-card>
            
            <el-card class="form-card" shadow="never">
              <template #header>
                <div class="form-header">
                  <span>描述信息</span>
                </div>
              </template>
              <el-form-item label="描述">
                <el-input
                  v-model="addForm.description"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入描述"
                />
              </el-form-item>
            </el-card>

          
            <el-card class="form-card" shadow="never">
              <template #header>
                <div class="form-header">
                  <span>计算公式</span>
                </div>
              </template>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="单重公式">
                    <el-input
                      v-model="addForm.weightJudgment"
                      type="textarea"
                      :rows="3"
                      placeholder="请输入单重判定公式"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="单面积公式">
                    <el-input
                      v-model="addForm.areaJudgment"
                      type="textarea"
                      :rows="3"
                      placeholder="请输入单面积判定公式"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="总重公式">
                    <el-input
                      v-model="addForm.weightTotalJudgment"
                      type="textarea"
                      :rows="3"
                      placeholder="请输入总重判定公式"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="总面积公式">
                    <el-input
                      v-model="addForm.areaTotalJudgment"
                      type="textarea"
                      :rows="3"
                      placeholder="请输入总面积判定公式"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-card>

          </el-form>
        </div>
      </template>
    </sys-dialog>
  </el-main>
</template>

<style scoped lang="scss">
.material-category-main {
  padding: 0;
}

.main-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.tree-card {
  border-radius: 8px;
  height: calc(100vh - 100px);
  
  .tree-header {
    padding: 12px 0;
    margin-bottom: 10px;
    display: flex;
    align-items: center;
    font-size: 16px;
    font-weight: 600;
    color: #67c23a;
    border-bottom: 1px solid #e1f3d8;
    
    i {
      margin-right: 8px;
    }
  }
  
  .category-tree {
    height: calc(100vh - 160px);
    overflow: auto;
    
    :deep(.el-tree-node__content) {
      height: 36px;
      
      &:hover {
        background-color: #f0f9eb;
      }
    }
    
    :deep(.el-tree-node.is-current > .el-tree-node__content) {
      background-color: #e1f3d8;
      color: #67c23a;
    }
  }
}

.search-card {
  margin-bottom: 20px;
  border-radius: 8px;
  transition: all 0.3s;
  
  :deep(.el-card__body) {
    padding: 15px 20px;
  }
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  
  .el-form-item {
    margin-bottom: 0;
    margin-right: 16px;
  }
  
  .search-buttons {
    margin-left: auto;
    
    .el-button {
      margin-left: 8px;
      transition: all 0.3s;
      
      &:first-child {
        margin-left: 0;
      }
    }
    
    .search-btn {
      background: linear-gradient(135deg, #1989fa, #0056b3);
      border: none;
      
      &:hover {
        opacity: 0.9;
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(25, 137, 250, 0.3);
      }
    }
    
    .add-btn {
      background: linear-gradient(135deg, #67c23a, #409eff);
      border: none;
      
      &:hover {
        opacity: 0.9;
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(103, 194, 58, 0.3);
      }
    }
    
    .reset-btn:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(144, 147, 153, 0.2);
    }
  }
}

.table-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  height: calc(100vh - 180px);
  margin-bottom: 0;
  
  :deep(.el-card__body) {
    padding: 0;
    height: 100%;
    display: flex;
    flex-direction: column;
  }
}

.data-table {
  border-radius: 4px;
  flex: 1;
  
  :deep(.el-table__header-wrapper) {
    th {
      background-color: #f2f6fc;
      font-weight: 600;
    }
  }
  
  :deep(.el-table__row) {
    &:hover {
      td {
        background-color: #ecf5ff;
      }
    }
  }
  
  .action-buttons {
    display: flex;
    justify-content: center;
    
    .el-button {
      padding: 6px 10px;
      transition: all 0.3s;
      
      &:hover {
        transform: translateY(-2px);
      }
    }
    
    .edit-btn {
      margin-right: 10px;
    }
  }
}

.pagination {
  padding: 15px 20px;
  justify-content: flex-end;
  background: #fff;
  border-radius: 0 0 8px 8px;
}

.dialog-content {
  padding: 10px;
}

.add-form {
  .form-card {
    margin-bottom: 15px;
    border-radius: 8px;
    transition: all 0.3s;
    overflow: hidden;
    border: 1px solid #ebeef5;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    :deep(.el-card__header) {
      padding: 10px 15px;
      background: linear-gradient(90deg, #f0f9eb, #e1f3d8);
      border-bottom: 1px solid #e1f3d8;
    }
    
    .form-header {
      font-size: 16px;
      font-weight: 600;
      color: #67c23a;
    }
  }
  
  :deep(.el-input), :deep(.el-select), :deep(.el-tree-select) {
    width: 100%;
  }
  
  :deep(.el-input__wrapper), :deep(.el-textarea__inner) {
    box-shadow: 0 0 0 1px #dcdfe6 inset;
    
    &:hover {
      box-shadow: 0 0 0 1px #c0c4cc inset;
    }
    
    &.is-focus {
      box-shadow: 0 0 0 1px #67c23a inset;
    }
  }
  
  :deep(.el-form-item__label) {
    font-weight: 500;
  }
}

.full-width {
  width: 100%;
}

.code-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
  line-height: 1.5;
}
</style>
